package service

import (
	"gitee.com/spellbreaker/FogGoService/fogcore"
	socketio "github.com/googollee/go-socket.io"
	"sync"
	"time"
)

type Rooms struct {
	playerMap map[string]*GameRoom //rid=>GameRoom 通过房间id获取具体的房间
	rLock     sync.RWMutex         //加锁
}

func (rs *Rooms) GetGameRoomByRID(rid string) *GameRoom {
	rs.rLock.RLock()
	defer rs.rLock.RUnlock()
	return rs.playerMap[rid]
}

func (rs *Rooms) DeleteGameRoomByRID(rid string) {
	rs.rLock.Lock()
	defer rs.rLock.Unlock()
	delete(rs.playerMap, rid)
}

func (rs *Rooms) AppendGameRoom(rid string, room *GameRoom) bool {
	rooms.rLock.Lock()
	defer rooms.rLock.Unlock()
	if _, ok := rooms.playerMap[rid]; ok {
		return false
	}
	rs.playerMap[rid] = room
	return true
}

type GameState int

const (
	NOT_START    GameState = 0
	GAME_STARTED GameState = 1
	GAME_OVER    GameState = 2
)

type GameRoom struct {
	fogGo     *fogcore.FogGoGame   //游戏
	gameState GameState            //游戏进行的状态
	gsmap     map[string]*GameSelf //uid => GameSelf
	gLock     sync.RWMutex         //加锁
}

func (gr *GameRoom) getOpponent(uid string) *GameSelf {
	for k := range gr.gsmap {
		if k != uid {
			return gr.gsmap[k]
		}
	}
	return nil
}

//GameSelf 保存下棋方的信息
type GameSelf struct {
	uid        string              //用户id
	username   string              //用户名
	color      fogcore.PointStatus //用户是黑方还是白方
	mask       *fogcore.FogGoGame  //视图，被迷雾遮蔽过的棋盘
	conn       socketio.Conn       //socket.io的连接
	rt         time.Duration       //剩余时间
	lastP      time.Time           //上一次落子的时间
	disconnect bool                //退出连接了
}
